package triangleWorm;

import processing.core.*;

public class SimpleWorm3D implements IWorm{
	//Parent
	PApplet p;
	
	//Worm movement
	IWormMovement m;
	
	//Worm 'parts'
	int elementNum = 15;	
	PVector[] elements = new PVector[elementNum];
	float elementMaxDist = 10f;
	float elementDistDamp = 1f / 3f;
	float elementEllipseSize = 5f;
	
	
	float wormLenth = elementNum * elementMaxDist;
	
	//Colors
	int[] elementColors = new int[elementNum];
	float averageColorIntensity = 150;
	float sumOfColorIntensity = averageColorIntensity * 3;
	
	public SimpleWorm3D(){
		//Init parts
		for(int i = 0; i < elementNum; i ++) {
			elements[i] = new PVector();
		}
	}

	public void init(PApplet processing, IWormMovement movement) {
		//Get parent
		p = processing;
		
		//Get movement
		m = movement;
		
		//Setup parts
		for(int i = 0; i < elements.length; i ++) {
			//Position
			elements[i].set(m.getPosition());
			
			//Setup color
			float colorPart1 = sumOfColorIntensity;
			float colorPart2 = sumOfColorIntensity;
			//Get random intervals
			while(colorPart1 >= colorPart2 || colorPart1 > 255f || colorPart2 - colorPart1 > 255f || sumOfColorIntensity - colorPart2 > 255f) {
				colorPart1 = p.random(sumOfColorIntensity);
				colorPart2 = p.random(sumOfColorIntensity);
			}
			//
			float red = colorPart1;
			float green = colorPart2 - colorPart1;
			float blue = sumOfColorIntensity - colorPart2;
			
			//Color first part white (for debugging)
			if(i > 0) {
				elementColors[i] = p.color(red, green, blue);				
			} else {
				elementColors[i] = p.color(255, 255, 255);				
			}
		}		
	}

	public void update() {
		//Update movement
		m.update();
		
		//Set position of first element
		elements[0].set(m.getPosition());
		
		PVector diff;
		for(int i = 1; i < elements.length; i ++) {
			//If element is too far away
			if(elements[i].dist(elements[i - 1]) > elementMaxDist) {
				//Get the vector FROM element[i] to element[i +1]
				diff = PVector.sub(elements[i - 1], elements[i]);
				//'Damp' vector
				diff.mult(elementDistDamp);
				//Add vector
				elements[i].add(diff);
			}
		}
	}

	public void draw() {
		//Iterate over all elements
		for(int i = 0; i < elementNum; i ++) {
			//Set color
			p.fill(elementColors[i]);
			
			/* Draw as ellipses 
			p.pushMatrix();
				//Move to element position
				p.translate(elements[i].x, elements[i].y, elements[i].z);
				p.ellipse(0f, 0f, elementEllipseSize, elementEllipseSize);
			p.popMatrix(); 
			*/

			//Draw as lines
			p.stroke(elementColors[i]);
			p.line(elements[i].x, elements[i].y, elements[i].z, elements[i - 1].x, elements[i - 1].y, elements[i - 1].z);
			p.noStroke();
		}
	}

	public PVector getPosition() {
		return m.getPosition();
	}
	
	public float getLength() {
		return wormLenth;
	}

}
